package com.oa.android.adapter;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.oa.android.R;
import com.oa.android.activity.DbWrokActivity;
import com.oa.android.entry.FileM;
import com.oa.android.utils.FileMange;
import com.oa.android.utils.UConstants;
import com.oa.android.utils.Util;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;

/**
 * Created by zouqh on 2016/6/16.
 */
public class FileMangeAdapter extends BaseAdapter {
    private   String filePath = Environment.getExternalStorageDirectory().getPath() + File.separator+"ZHOA"+ File.separator;
    private Context context;
    private List<FileM> mList;
    private ProgressDialog progressDialog;
    private FileMange fileMange;

    public FileMangeAdapter(Context context, List<FileM> list) {
        this.context = context;
        this.mList = list;
        fileMange=new FileMange(context);
    }

    @Override
    public int getCount() {
        return this.mList.size();
    }

    @Override
    public Object getItem(int position) {
        return mList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        int temp=-1;
        ViewHolder viewHolder;
        if (convertView == null) {
            convertView = LayoutInflater.from(context).inflate(R.layout.file_item, null);
            viewHolder = new ViewHolder(convertView);
            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }

        final FileM fileM = mList.get(position);
        viewHolder.name.setText(fileM.getFILENAME());

        if (fileM.getDFBZ() != null) {
            if (fileM.getDFBZ().equals("1")) {
                viewHolder.fileImg.setImageResource(R.drawable.icon_dir);
                viewHolder.ritghImg.setImageResource(R.drawable.file_arrow);
                temp=0;
            } else if (fileM.getDFBZ().equals("0")) {
                viewHolder.fileImg.setImageResource(R.drawable.icon_pdf_file);
                if (new File(filePath+fileM.getFILENAME()).exists()){
                    viewHolder.ritghImg.setImageResource(R.drawable.open_file_icon);
                    temp=1;
                }else {
                    viewHolder.ritghImg.setImageResource(R.drawable.down_file_icon);
                    temp=2;
                }
            }
        }

        final int finalTemp = temp;
        viewHolder.ritghImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (finalTemp ==1){//打开文件
                    fileMange.openFile(new File(filePath+fileM.getFILENAME()));
                }else  if (finalTemp ==2){//下载文件

                    if (Util.NoNull(fileM.getFILEPATH())){

                        String[] bs= fileM.getFILEPATH().split("/");
                        StringBuffer brf = new StringBuffer();
                        for (int i = 0; i < bs.length; i++) {
                            if(i==bs.length-1){

                                try {
                                    brf.append(URLEncoder.encode(bs[i],"UTF-8").replaceAll("\\+", "%20"));
                                } catch (UnsupportedEncodingException e) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                                }
                            }else {
                                brf.append(bs[i]).append("/");
                            }

                        }
                        downloadFile(UConstants.URL_DOWN+brf.toString(),filePath+fileM.getFILENAME());

                    }else{
                        Toast.makeText(context,"下载地址有误",Toast.LENGTH_SHORT).show();
                    }

                }
            }
        });


        return convertView;
    }


    static class ViewHolder {
        @InjectView(R.id.fileImg)
        ImageView fileImg;
        @InjectView(R.id.name)
        TextView name;
        @InjectView(R.id.ritghImg)
        ImageView ritghImg;

        ViewHolder(View view) {
            ButterKnife.inject(this, view);
        }
    }

    private void downloadFile(final String url, String path) {
        progressDialog = new ProgressDialog(context);
        RequestParams requestParams = new RequestParams(url);
        requestParams.setSaveFilePath(path);
        x.http().get(requestParams, new Callback.ProgressCallback<File>() {
            @Override
            public void onWaiting() {
            }

            @Override
            public void onStarted() {
            }

            @Override
            public void onLoading(long total, long current, boolean isDownloading) {
                progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                progressDialog.setMessage("下载中...");
                progressDialog.show();
                progressDialog.setMax((int) total);
                progressDialog.setProgress((int) current);
            }

            @Override
            public void onSuccess(File result) {
                Toast.makeText(context, "下载成功", Toast.LENGTH_SHORT).show();
                progressDialog.dismiss();
                notifyDataSetChanged();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                ex.printStackTrace();
                Toast.makeText(context, "下载失败，文件不存在或者网络问题", Toast.LENGTH_SHORT).show();
                progressDialog.dismiss();
            }

            @Override
            public void onCancelled(CancelledException cex) {
            }

            @Override
            public void onFinished() {
            }
        });
    }
}
